import { _decorator, Collider2D, Component, Contact2DType, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('EnemyBullet')
export class EnemyBullet extends Component {

    @property
    speed:number = 300;

    collider:Collider2D = null;

    start() {
        this.collider = this.getComponent(Collider2D);
        if(this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }

    update(deltaTime: number) {
        const position = this.node.position;

        // let angle:number = this.node.angle;
        // let deltaX = this.speed*deltaTime*Math.sin(angle);
        // let deltaY = this.speed*deltaTime*Math.abs(Math.cos(angle));

        this.node.setPosition(position.x, position.y - this.speed*deltaTime, position.z);

        let newPosition = this.node.getPosition();
        if(newPosition.y < -435 || newPosition.x > 250 || newPosition.x < -250) {
            this.node.destroy();
            console.log('bullet destroy ...');
        }
    }

    onBeginContact() {
        this.scheduleOnce(function() {
            this.node.destroy();
        }, 0.02);
    }

    protected onDestroy(): void {
        if(this.collider) {
            this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }
}

